from flask import Blueprint, request, render_template, session, redirect, jsonify
from config import db
from models.models import User
from utils.utils import md5, get_now_data_time
from wtforms.validators import Length
import wtforms

login_service = Blueprint('login_service', __name__)


class LoginForm(wtforms.Form):
    username = wtforms.StringField(validators=[Length(min=1, message='用户名格式错误')])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message='密码格式错误')])


@login_service.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        form = LoginForm(request.form)
        if form.validate():
            username = form.username.data
            password = form.password.data
            password = md5(username, password)
            user = User.query.filter_by(username=username).first()
            if not user:
                return redirect('/login')
            if user.password == password:
                session['user_id'] = user.id
                user.loginTime = get_now_data_time()
                db.session.commit()
                return redirect('/')
            else:
                return redirect('/login')
    else:
        return render_template('loginnew.html')


@login_service.route('/admin')
def index():
    return render_template('admin_index.html')


@login_service.route('/loginout')
def login_out():
    session.clear()
    return redirect('/')
